import json
from typing import List

from fastapi import Depends, APIRouter
from pydantic import BaseModel

from api.acl.role import GetRoles,Add_role,Get_menus_buttons,Get_menus_buttons_by_roleid,Add_role_acls
from util.JWT import get_current_user

acl_role = APIRouter()

# 获取所有角色
@acl_role.get("/roles")
async def roles(page: int = 1, page_size: int = 10,id: dict = Depends(get_current_user)):
    df = GetRoles()
    if df.empty:
        return {
            "code": 204,
            "status": "no",
            "msg": "没有内容",
            "data": {}
        }
    df.fillna('', inplace=True)
    total = len(df)
    offset = (page - 1) * page_size
    df = df.iloc[offset: offset + page_size]
    # 将DataFrame转换为字典列表
    dict_list = df.to_dict(orient='records')
    # 将字典列表转换为指定格式的JSON字符串
    return {
        "code": 200,
        "status": "ok",
        "msg": "success",
        "total": total,
        "data": dict_list
    }

# 添加用户
class AddRoleType(BaseModel):
    rolename: str
@acl_role.post("/add_role")
async def add_role(data: AddRoleType, id: dict = Depends(get_current_user)):
    i = Add_role(data.rolename)
    if i == 1:
        return {
            "code": 200,
            "status": "ok",
            "msg": "添加成功",
            "data": {}
        }
    else:
        return {
            "code": 204,
            "status": "no",
            "msg": "添加失败",
            "data": {}
        }

# 递归函数来构建层级列表
def build_hierarchy(df,rolacList, parent_id=None, level=1):
    result = []
    for index, row in df.iterrows():
        if row['parent_id'] == parent_id:
            row_dict = row.to_dict()
            row_dict['level'] = level
            # 检查角色是否拥有该权限
            row_dict['has_permission'] = row['acl_id'] in rolacList
            children = build_hierarchy(df,rolacList, row['acl_id'], level + 1)
            if children:
                row_dict['children'] = children
            result.append(row_dict)
    return result
@acl_role.get("/get_menus_buttons") # 获取菜单和按钮
async def get_menus_buttons(role_id,id: dict = Depends(get_current_user)):
    df = Get_menus_buttons()

    df1=Get_menus_buttons_by_roleid(role_id)
    rolacList=[]
    if not df1.empty:
        rolacList=df1['acl_id'].to_list() # 获取角色id所在的权限
    if df.empty:
        return {
            "code": 204,
            "status": "no",
            "msg": "没有内容",
            "data": {}
        }
    else:
        # 找到顶层节点，即 parent_id 为 None 的节点
        top_level_nodes = df[df['parent_id']==0]

        # 构建层级列表
        hierarchy_list = []
        for index, top_node in top_level_nodes.iterrows():
            top_node = top_node.fillna(0)  # 将 NaN 替换为 0
            node_dict = top_node.to_dict()
            node_dict['level'] = 0 if top_node['parent_id'] == 0 else 1  # 根据顶级节点判断 level
            # 检查角色是否拥有该权限
            node_dict['has_permission'] = top_node['acl_id'] in rolacList
            node_dict['level'] = 1
            children = build_hierarchy(df,rolacList, top_node['acl_id'], 2)
            if children:
                node_dict['children'] = children
            hierarchy_list.append(node_dict)

        # 在最外层再套一个最顶层的节点，叫做 "全部数据"
        all_data = {
            "acl_id": 0,  # 或者是其他适当的空值，表示这是一个虚拟节点
            "parent_id": 0,
            "acl_name": '',
            "acl_type": '',  # 或者是其他适当的空值，表示这是一个虚拟节点
            "title": '全部数据',  # 或者是其他适当的空值，表示这是一个虚拟节点
            "level": 0,  # 设置 level 为 0
            "has_permission": False,  # 或者根据实际情况设定
            "children": hierarchy_list
        }

        # 序列化为 JSON，并设置ensure_ascii=False保留中文字符
        json_data = json.dumps(all_data, indent=4, ensure_ascii=False)
        # 返回 JSON 数据
        return {
            "code": 200,
            "status": "ok",
            "msg": "添加成功",
            "data": json_data
        }

class AddRoleAclType(BaseModel):
    role_id: int
    acls: List[int]
@acl_role.post("/add_role_acl")
async def add_role_acl(data: AddRoleAclType, id: dict = Depends(get_current_user)):
    sqlList=[]
    sqlList.append(("DELETE role_acl WHERE role_id = ?", [data.role_id]))
    for v in data.acls:
        sqlList.append(("INSERT INTO role_acl(role_id, acl_id) VALUES(?, ?)", [data.role_id, v]))
    if Add_role_acls(sqlList):
        return {
            "code": 200,
            "status": "ok",
            "msg": "添加成功",
            "data": {}
        }
    else:
        return {
            "code": 204,
            "status": "no",
            "msg": "添加失败",
            "data": {}
        }







